<!--2019-12-17备份续住功能-->
<template>
  <div class="order-details">
    <div class="status" :class="statusBg">
    </div>
    <a-row>
      <a-col :span="24">
        <div class="fwdz">
          {{ details.fwdz }}{{ details.fh }}&emsp;
        </div>
      </a-col>
    </a-row>
    <div class="title">入住人员</div>
    <a-row v-for="(tenant, index) in order.tenantList" :key="index" class="orderrow">
      <a-col :span="10"><span>入住人：{{ tenant.zkxm }} {{ tenant.lxdh }}</span></a-col>
      <a-col :span="4">
        <span v-if="tenant.rzbz === '2'"> <a-icon :component="iconNotcertified" style="margin-right:5px"/>未认证</span>
        <span v-else><a-icon :component="iconVerified" style="margin-right:5px"/>已认证</span>
      </a-col>
      <a-col :span="10"><span>身份证：{{ tenant.zjhm }}</span></a-col>
    </a-row>
    <div class="title pad_top28">入住时间</div>
    <a-row v-if="overStayStatus">
      <a-form :form="overStayOrderForm">
        <a-col :span="6">
          <a-form-item>
            <a-date-picker
              showTime
              format="YYYY-MM-DD HH:mm:ss"
              :disabled="overStayStatus"
              v-decorator="[
                `rzsj`,{
                  rules: [{
                    required: true,
                    message: '请选择开始时间'
                  }],
                  initialValue:moment(order.rzsj)
                }
              ]"
              placeholder="开始时间" />
          </a-form-item>
        </a-col>
        <a-col :span="2"><div class="times">共{{ timesCup }}晚</div></a-col>
        <a-col :span="6">
          <a-form-item>
            <a-date-picker
              dropdownClassName="jlwDate"
              showTime
              format="YYYY-MM-DD HH:mm:ss"
              :disabledDate="disabledDate"
              @change="onChange"
              v-decorator="[
                `ldsj`,{
                  rules: [{
                    required: true,
                    message: '请选择结束时间'
                  }, {validator: validate}],
                  initialValue: moment(order.ldsj)
                }
              ]"
              placeholder="结束时间" >
              <template slot="dateRender" slot-scope="current,tody">
                <div class="ant-calendar-date" :style="getCurrentStyle(current,tody)">
                  {{ current.date() }}
                  <span v-if="includesArray(current) === 1" style="font-size:12px;"><br/>预定</span>
                  <span v-else-if="includesArray(current) === 2" style="font-size:12px;"><br/>已住</span>
                </div>
              </template>
              <template slot="renderExtraFooter"><span id="msgClass">{{ msg }}</span></template>
            </a-date-picker>
          </a-form-item>
        </a-col>
      </a-form>
    </a-row>
    <a-row v-else>
      <a-col :span="10"><span>{{ order.rzsj }}</span></a-col>
      <a-col :span="4"><span>共{{ order.rzts }}晚</span></a-col>
      <a-col :span="10">{{ order.ldsj }}</a-col>
    </a-row>
  </div>
</template>
<script>
import moment from 'moment'
import { iconNotcertified, iconVerified } from '@/core/icons'
import { reletOrder, getOrdersByHouseId } from '@/api/order'
import { timesDate } from '@/utils/util'
export default {
  name: 'OrderDetail',
  props: {
    details: {
      type: Object,
      default: () => {
        return {}
      }
    },
    overStayStatus: {
      type: Boolean,
      default: false
    },
    orderManage: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      overStayOrderForm: this.$form.createForm(this),
      iconNotcertified,
      iconVerified,
      times: 1, // 共几晚
      msg: '', // 日历页脚消息提示
      pickDisabled: []
    }
  },
  computed: {
    statusBg () {
      const ddzt = this.order.ddzt
      let bgImg = ''
      switch (ddzt) {
        case '1':
          bgImg = `icon-wait`
          break
        case '2':
          bgImg = `icon-check-in`
          break
        case '3':
          bgImg = `icon-retreat`
          break
        case '4':
          bgImg = `icon-cancel`
          break
      }
      return bgImg
    },
    /* 判断是不是来源
    *orderManage 代表是入住管理来的
    */
    order () {
      if (this.orderManage === 'orderManage') {
        return this.details
      } else {
        return this.details['orderList'][0]
      }
    },
    timesCup () {
      return this.times
    }
  },
  mounted () {
    this.times = this.order.rzts
  },
  created () {
    if (this.overStayStatus) {
      /* 获取日历数据传入房号 houseId */
      const cxsj = moment(this.order.rzsj).format('YYYY-MM-DD HH:mm:ss')
      this.getPickDate(this.details.houseId, cxsj)
    }
  },
  methods: {
    moment,
    /** 日历插件时间change */
    onChange (value, dateString) {
      const dateArray = this.pickDisabled
      if (this.pickDisabled.length > 0) {
        let isfalse = true
        for (let i = 0; i < dateArray.length; i++) {
          if (moment(value).isBefore(dateArray[i]['rzsj']) || moment(this.order.rzsj).isAfter(dateArray[i]['ldsj'])) {
            continue
          } else {
            isfalse = false
            break
          }
        }
        if (isfalse) {
          this.msg = ''
        } else {
          this.msg = '所选时间已有房源被占用'
        }
      } else {
        this.msg = ''
      }
      this.totalDate(value, dateString)
    },
    // 日期禁用
    disabledDate (currentDate) {
      const dateArray = this.pickDisabled
      if (currentDate) {
        if (currentDate <= moment(this.order.ldsj || new Date()).add(0, 'days').endOf('day')) {
          return true
        } else {
          for (let i = 0; i < dateArray.length; i++) {
            if (currentDate.isBetween(dateArray[i]['rzsj'], dateArray[i]['ldsj']) || currentDate.isSame(dateArray[i]['rzsj']) || currentDate.isSame(dateArray[i]['ldsj'])) {
              return true
            }
          }
        }
      }
    },
    // 日历插槽样式
    getCurrentStyle (currentDate) {
      const dateArray = this.pickDisabled
      const style = {}
      style.width = '46px'
      style.minWidth = '46px'
      style.height = '46px'
      style.lineHeight = '46px'
      for (let i = 0; i < dateArray.length; i++) {
        if (currentDate.isBetween(dateArray[i]['rzsj'], dateArray[i]['ldsj']) || currentDate.isSame(dateArray[i]['rzsj']) || currentDate.isSame(dateArray[i]['ldsj'])) {
          style.position = 'relative'
          style.lineHeight = '1.5'
        }
      }
      return style
    },
    // 日历订单状态（）
    includesArray (currentDate) {
      const dateArray = this.pickDisabled
      for (let i = 0; i < dateArray.length; i++) {
        if (currentDate.isBetween(dateArray[i]['rzsj'], dateArray[i]['ldsj']) || currentDate.isSame(dateArray[i]['rzsj']) || currentDate.isSame(dateArray[i]['ldsj'])) {
          if (dateArray[i]['ddzt'] === '1') {
            return 1
          } else if (dateArray[i]['ddzt'] === '2') {
            return 2
          }
        }
      }
    },
    disabledDateTime () {
      const hours = new Date(this.order.ldsj).getHours()
      return {
        disabledHours: () => this.range(0, 24).splice(0, hours)
      }
    },
    handleSubmit (val) {
      return new Promise((resolve, reject) => {
        // e.preventDefault()
        const orderRequest = {
          rzsj: '',
          ldsj: '',
          fwdz: this.details.fwdz,
          fh: this.details.fh,
          houseId: this.details.houseId,
          hoperatorId: val.hoperatorId,
          storesId: val.storesId,
          jylx: val.OPERATOR_TYPE,
          orderId: this.order.orderId
          // tenantsRequest: ''
        }
        this.overStayOrderForm.validateFieldsAndScroll(async (err, values) => {
          if (!err) {
            orderRequest.rzsj = values['rzsj'].format('YYYY-MM-DD HH:mm:ss')
            orderRequest.ldsj = values['ldsj'].format('YYYY-MM-DD HH:mm:ss')
            const res = await reletOrder(orderRequest).catch((err) => {
              reject(err)
            })
            if (res.code === 2017) {
              let conflictStr = ''
              for (let i = 0; i < res.data.length; i++) {
                if (values['ldsj'].isBefore(res.data[i]['rzsj']) || values['rzsj'].isAfter(res.data[i]['ldsj'])) {
                  continue
                } else {
                  conflictStr += `${res.data[i]['rzsj']}--${res.data[i]['ldsj']};`
                  break
                }
              }
              conflictStr = `${conflictStr}已有订单，请重新选择！`
              this.$notification['warning']({
                message: this.$t('message.hint'),
                description: conflictStr,
                duration: 10
              })
              reject(err)
            } else {
              resolve(res)
            }
          } else {
            reject(err)
          }
        })
      })
    },
    // 多少晚
    totalDate (date, dateString) {
      if (dateString !== '') {
        this.times = timesDate(this.order.rzsj, dateString)
      } else {
        this.times = 0
      }
    },
    // 获取后台数据禁用数据获取日历
    getPickDate (houseId, curDate) {
      getOrdersByHouseId({ houseId: houseId, cxsj: curDate }).then((res) => {
        const firstOrderId = this.order.orderId // 默认展示第一条数据
        if (firstOrderId && firstOrderId !== 0) {
          if (res.data && res.data.length > 0) {
            const list = res.data.filter((item) => {
              if (item.orderId !== firstOrderId) {
                return item
              }
            })
            this.pickDisabled = list
          } else {
            this.pickDisabled = res.data
          }
        } else {
          this.pickDisabled = res.data
        }
      }).catch((error) => console.log(error))
    },
    validate (rule, value, callback) {
      const firstOrder = this.order
      if (value) {
        const star = moment(firstOrder.ldsj)
        const end = moment(value)
        if (end <= star) {
          callback(new Error('不能小于/等于离店时间'))
        }
        const dateArray = this.pickDisabled
        let isfalse = true
        for (let i = 0; i < dateArray.length; i++) {
          if (moment(value).isBefore(dateArray[i]['rzsj']) || moment(firstOrder.rzsj).isAfter(dateArray[i]['ldsj'])) {
            continue
          } else {
            isfalse = false
            break
          }
        }
        if (isfalse) {
          callback()
        } else {
          callback(new Error('所选时间已有房源被占用'))
        }
      } else {
        callback()
      }
    }
  }
}
</script>
<style lang="less" scoped>
.order-details {
  position: relative;

  .fwdz {
    height: 24px;
    font-size: 16px;
    font-weight: 700;
    color: rgba(0, 0, 0, 0.85);
    line-height: 24px;
    // margin-top: 24px;
  }

  .title {
    width: 56px;
    height: 16px;
    font-size: 14px;
    font-weight: 700;
    color: rgba(51, 51, 51, 1);
    line-height: 16px;
    margin-bottom: 22px;
  }

  .status {
    position: absolute;
    top: 15px;
    right: -24px;
    width: 59px;
    height: 26px;
  }

  .icon-check-in {
    background-image: url("../../../../assets/icon-check-in.png");
    background-position: center center;
    background-size: cover;
  }

  .icon-wait {
    background-image: url("../../../../assets/icon-wait.png");
    background-position: center center;
    background-size: cover;
  }
  .icon-cancel {
    background-image: url("../../../../assets/icon-cancel.png");
    background-position: center center;
    background-size: cover;

  }
  .icon-retreat {
    background-image: url("../../../../assets/icon-retreat.png");
    background-position: center center;
    background-size: cover;
  }

  .times {
    width: 100%;
    text-align: center;
    position: absolute;
    top: 10px;
  }
}
#msgClass{color:red;}
</style>
